package com.gm.census.service.impl;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.gm.census.model.pojo.Ask;
import com.gm.census.service.AskService;
import com.gm.census.service.BaseService;
import com.gm.census.service.PagedListResult;
import com.google.appengine.api.datastore.Cursor;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class AskServiceImpl extends BaseServiceImpl<Ask, Long> implements
		AskService {

	static {
		ObjectifyService.register(Ask.class);
	}
	private static final Logger log = Logger.getLogger(AskServiceImpl.class
			.getName());

	private Key<String> parent() {
		return new Key<String>(String.class, "admin");
	}

	private Key<Ask> key(Long id) {
		return new Key<Ask>(parent(), Ask.class, id);
	}

	@Override
	public Ask find(final Long id) {
		return inNs(new DefaultNSCmd<Ask>() {

			@Override
			public Ask execute() {
				return begin().find(key(id));
			}

		});
	}

	@Override
	public Ask put(final Ask ask) {
		return inNs(new DefaultNSCmd<Ask>() {
			@Override
			public Ask execute() {
				ask.setTimestamp(new Date());
				ask.setParent(parent());
				Key<Ask> k = begin().put(ask);
				ask.setId(k.getId());
				return ask;
			}
		});

	}

	@Override
	public void delete(final Long id) {
		inNs(new DefaultNSCmd<String>() {

			@Override
			public String execute() {
				begin().delete(key(id));
				return null;
			}

		});
	}

	@Override
	public Ask get(final Long id) {
		return inNs(new DefaultNSCmd<Ask>() {
			@Override
			public Ask execute() {
				return begin().get(key(id));
			}
		});
	}

	@Override
	public Ask findByEmail(final String email) {
		return inNs(new DefaultNSCmd<Ask>() {
			@Override
			public Ask execute() {
				return begin().query(Ask.class).ancestor(parent())
						.filter("email =", email).get();
			}
		});
	}

	@Override
	public List<Ask> list() {
		return list(null, 0).getReturn();
	}

	@Override
	public GAEPagedListResult<Ask> list(final String index,
			final Integer pageSize) {
		return inNs(new DefaultNSCmd<GAEPagedListResult<Ask>>() {
			@Override
			public GAEPagedListResult<Ask> execute() {
				Query<Ask> q = begin().query(Ask.class).ancestor(parent());
				if (pageSize > 0)
					q.limit(pageSize);
				else
					q.limit(BaseService.DEFAULT_QUERY_PAGE);

				if (index != null && index.length() > 0) {
					Cursor cursor = Cursor.fromWebSafeString(index);
					q.startCursor(cursor);
				}
				return new GAEPagedListResult<Ask>(q.iterator());

			}
		});
	}

	@Override
	public PagedListResult<List<Ask>> list(String index) {
		return list(index, 0);
	}

}
